import axios from 'axios';
import qs from 'qs';
import { Notify } from 'vant';

class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl;
    this.queue = {};
  }
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
        agent: 'Web',
      },
    };
    return config;
  }
  destroy(url) {
    delete this.queue[url];
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(
      config => {
        // 添加全局的loading...
        // ////console.log(config.data instanceof Object)
        if (config.method === 'post') {
          config.headers['content-type'] = 'application/x-www-form-urlencoded';
          config.data = qs.stringify(config.data);
        }
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );
    // 响应拦截
    instance.interceptors.response.use(
      res => {
        this.destroy(url);
        const { data, status } = res;
        if (status === '503') {
          Notify({
            message: data.msg,
            duration: 2000,
            background: '#ed4014',
          });
        }
        return { data, status };
      },
      error => {
        this.destroy(url);
        return Promise.reject(error);
      }
    );
  }
  request(options) {
    const instance = axios.create();
    options = Object.assign(this.getInsideConfig(), options);
    this.interceptors(instance, options.url);
    return instance(options);
  }
}
export default HttpRequest;
